package com.javaex.book.utils;

import java.security.MessageDigest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MD5加密工具类
 *
 * @author 黄星琦
 * @Date 2022年6月1日
 */
public class MD5Utils {
	
	private static final Logger log = LoggerFactory.getLogger(MD5Utils.class);

	/**
	 * MD5加密字符串
	 * @param str 将要加密的字符串
	 * @return 加密后的字符串
	 */
	public static String md5(String str) {
		MessageDigest algorithm;
		try {
			algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(str.getBytes("UTF-8"));
			byte[] messageDigest = algorithm.digest();
			StringBuffer buffer = new StringBuffer(messageDigest.length * 2);
			for (byte b : messageDigest) {
				if ((b & 0xff) < 0x10) {
					buffer.append("0");
				}
				buffer.append(Long.toString(b & 0xff, 16));
			}
			return buffer.toString();
		} catch (Exception e) {
			log.error("MD5 Error...", e);
		} 
		return null;
	}
}
